package com.earth.a.controller;


import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.earth.c.controller.BaseController;
import com.earth.c.plugins.shiro.CaptchaUsernamePasswordToken;
import com.earth.c.plugins.shiro.ShiroKit;
import com.earth.c.plugins.shiro.ShiroRealm;
import com.earth.c.plugins.shiro.SimpleUser;

@Controller
@RequestMapping("/")
public class LoginController extends BaseController{
	

    @RequestMapping(value = "login", method = RequestMethod.GET)
	public String login() {
		return "login.html";
	}
    
	@RequestMapping(value = "doLogin", method = RequestMethod.POST)
	@ResponseBody
	public String doLogin(HttpServletRequest request,@RequestParam(name = "username") String username,
			@RequestParam(name = "password") String password) throws  Exception{
		CaptchaUsernamePasswordToken token = new CaptchaUsernamePasswordToken(username, password);
		try {
			Subject subject = SecurityUtils.getSubject();
			ThreadContext.bind(subject);
			if (subject.isAuthenticated()) {
				subject.logout();
				throw new Exception("登录失败！");
			} else {
				subject.login(token);
				SimpleUser simpleUser = ShiroKit.getLoginUser();
				simpleUser.setSessionId(subject.getSession().getId().toString());
				return renderSuccess("登录成功！", simpleUser);
			}
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}

	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		try {
			Subject currentUser = SecurityUtils.getSubject();
			RealmSecurityManager rsm = (RealmSecurityManager)SecurityUtils.getSecurityManager();  
			ShiroRealm realm = (ShiroRealm)rsm.getRealms().iterator().next(); 
			realm.clearCachedAuthorization();
			currentUser.logout();
			return renderSuccess("用户已经注销！");
		} catch (Exception e) {
			return renderSuccess("用户已经注销！");
		}
	}


}
